#ifndef _LOGMGR_H_
#define _LOGMGR_H_

#define LOG_IN_MEMORY_SIZE	50

class LogMgr
{
private:
	tstring tsFilename;
	std::deque<tstring> dLogInMemory;
	CRITICAL_SECTION	csMutexMemory;
	CRITICAL_SECTION	csMutexFile;

	void LockMemory()
	{
		EnterCriticalSection(&csMutexMemory);
	}
	void UnlockMemory()
	{
		LeaveCriticalSection(&csMutexMemory);
	}
	void WriteToFile(tstring &tsMsg)
	{
		EnterCriticalSection(&csMutexFile);
		FILE *fp = _tfopen(tsFilename.c_str(),_TEXT("a+"));
		if( fp!=NULL )
		{
			_ftprintf(fp,_TEXT("%s"),tsMsg.c_str());
			fclose(fp);
		}
		LeaveCriticalSection(&csMutexFile);
	}
public:
	void SetFile(tstring tsFile)
	{
		tsFilename = tsFile;
		tstring tsMsg = _TEXT("==========================================================\n");
		WriteToFile(tsMsg);
	}
	LogMgr()
	{
		InitializeCriticalSection(&csMutexMemory);
		InitializeCriticalSection(&csMutexFile);
	}
	~LogMgr()
	{
		DeleteCriticalSection(&csMutexMemory);
		DeleteCriticalSection(&csMutexFile);
	}
	int LogIt(tstring tsMsg)
	{
		SYSTEMTIME SysTime;
		GetLocalTime(&SysTime);
		TCHAR szTime[100];
		_stprintf(szTime,_TEXT("[%02d/%02d %02d:%02d:%02d]"),
					SysTime.wMonth,
					SysTime.wDay,
					SysTime.wHour,
					SysTime.wMinute,
					SysTime.wSecond);
		tsMsg = szTime + tsMsg + _TEXT("\r\n");

		LockMemory();

		dLogInMemory.push_back(tsMsg);
		if( dLogInMemory.size() > LOG_IN_MEMORY_SIZE )
		{
			dLogInMemory.pop_front();
		}
		UnlockMemory();

		WriteToFile(tsMsg);

		return 0;
	}
	int GetLog(tstring &tsLog)
	{
		tsLog = _TEXT("");
		LockMemory();

		std::deque<tstring>::iterator it;
		for(it=dLogInMemory.begin();it!=dLogInMemory.end();it++)
		{
			tsLog += *it;
		}
		UnlockMemory();
		return 0;
	}
};

#endif